﻿
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using SimpleTicketBooking.Models.Response;

namespace SimpleTicketBooking.Utils.Filters
{
    /// <summary>
    /// A global api response wrapper
    /// </summary>
    public class ResultWrapperFilter : ActionFilterAttribute
    {
        /// <summary>
        /// implement wrap logic here
        /// </summary>
        /// <param name="context"></param>
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
            var actionWrapper = controllerActionDescriptor?.MethodInfo.GetCustomAttributes(typeof(NoWrapperAttribute), false).FirstOrDefault();
            var controllerWrapper = controllerActionDescriptor?.ControllerTypeInfo.GetCustomAttributes(typeof(NoWrapperAttribute), false).FirstOrDefault();
            //if decorated with NoWrapperAttribute, wrap is not needed 
            if (actionWrapper != null || controllerWrapper != null)
            {
                return;
            }

            // implementation as required
            if (context.Result is ObjectResult)
            {
                var objectResult = context.Result as ObjectResult;
                if (objectResult?.Value == null)
                {
                    context.Result = new ObjectResult(ResponseResult<object>.Failed("not found！"));
                }
                else
                {
                    //if response already wrapped as ResponseResult<T>, no more action needed
                    if (objectResult.DeclaredType.IsGenericType 
                        && objectResult.DeclaredType?.GetGenericTypeDefinition() == typeof(ResponseResult<>))
                    {
                        return;
                    }

                    context.Result = new ObjectResult(ResponseResult<object>.Success(objectResult.Value));
                }
                return;
            }
        }
    }
}
